/*********************************************/
/*
GALAXY Common JS Codes
*/
$(function() {
	$.gx.fixUI();
	$(document).ajaxStop($.gx.fixUI);
	/**/	
	//class submit
	$('.submit').click(function() {
		$(this).parents('form').submit();
	});
	//ajax overlay
	$("#ajaxing").dialog({
		width:200,
		height:100,
		closeOnEscape:false,
		resizable:false,
		//modal:true,
		//draggable:false,
		autoOpen:false
	}).ajaxStart(function() {
		$(this).dialog('open');
	}).ajaxStop(function() {
		$(this).dialog("close");
	}).parent().find('.ui-dialog-titlebar-close').hide();
});

$.extend({
	gx:{
		fixUI:function() {
			$('.jqbutton').each(function() {
				$(this).button({
					icons:{
						primary:		$(this).attr('_icon') ? 'ui-icon-'+$(this).attr('_icon') : '',
						secondary:	$(this).attr('_icon2') ? 'ui-icon-'+$(this).attr('_icon2') : ''
					}
				});
			});
		},
		go:function(selector) {
			selector = $.gx.parseSelector(selector);
			if(!selector) return;
			if($.browser.msie) {//IE doesnt send referer at location.href=url
				selector[0].click();
			} else {
				location.href=selector.attr('href');
			}
		},
		setRange:function(x, a, b) {
			var t;
			if(a>b) {
				t=a;a=b;b=t;
			}
			if(x<a) return a;
			if(x>b) return b;
			return x;
		},
		showMessage:function(msg, fwd, options) {
			var $msg = $("<p>"+msg+"</p>");
			if(typeof fwd == 'string' && fwd.length>0) {
				setTimeout(function() {
					location = fwd;
				}, 2000);
				var bts = {'点此手动跳转': function() {
					location = fwd;
				}}
			} else if(fwd && typeof fwd == 'object' && fwd.run) {
				if(!fwd.delay) fwd.run.call($msg);
				else setTimeout(function() {
					fwd.run.call($msg);
				}, fwd.relay)
			} else {
				var bts = {'关闭': function() {
					$(this).dialog('destroy');
				}}
				setTimeout(function() {
					$msg.dialog('destroy');
				}, 2000);
			}
			$msg.dialog($.extend({
				width:200,
				height:100,
				closeOnEscape:false,
				modal:true,
				resizable:false,
				draggable:false,
				title:'提示信息',
				buttons:bts
			}, options));
		},
		parseResult:function(result) {
			if(typeof result == 'string') {
				result = $.parseJSON(result);
			}
			try {
				var status = parseInt(result.status);
				if(status==1) {//HTML code
					$('#body').html(result.data);
				} else if(status==2) {//showMessage
					var msg = result.info;
					var fwd = result.data;
					$.gx.showMessage(msg, fwd)
				}
			} catch(e) {
				$.gx.showMessage("服务器内部错误");
			}
		},
		parseSelector:function(selector) {
			var $obj;
			if(typeof selector=='object' && selector.jquery) $obj = selector;
			else if(typeof selector=='object' && selector.nodeType==1) $obj = $(selector);
			else if(typeof selector=='string' && selector.length > 0) $obj = $(selector);
			else if(typeof this=='object') $obj = $(this);
			else return false;
			return $obj;
		},
		parseError:function(xhr, text, error) {
			if(xhr.responseText) {
				var win = window.open("","","modal=1,depended=1");
				win.document.write(xhr.responseText);
			} else {
				alert('未知的错误:'+text);
			}
		},
		urlAppend:function(url, obj) {
			if(url.indexOf('?')==-1) url+='?'; else url+='&';
			url+=$.param(obj)
			return url;
		},
		ajaxForm:function(selector, options) {
			var $form = $.gx.parseSelector.call(this, selector);
			if(!$form) return false;
			
			if(typeof options != 'object') options = {};
			var cb_before = options.cb_before,
			cb_success = options.cb_success,
			cb_error = options.cb_error,
			dataType = options.dataType || 'json';
			if(!$form.jquery) $form = $($form);
			$form.each(function() {
				var form = this;
				if($(form).attr('action').indexOf('?') == -1) {
					$(form).attr('action', $(form).attr('action') + '?ajax=yes')
					.attr('method', 'POST');
				} else {
					$(form).attr('action', $(form).attr('action') + '&ajax=yes')
					.attr('method', 'POST');
				}
				$(form).ajaxForm({
					beforeSubmit:function() {
						if(cb_before) {
							return cb_before.call(form);
						} else {
							$(form).find('input:submit').each(function() {
								$(this).attr({
									'disabled': true,
									'_value': $(this).val(),
									'value': '请稍候...'
								});
							});
							return true;
						}
					},
					dataType:dataType,
					success:function(rst) {
						if(cb_success) {
							cb_success.call(form, rst);
						} else {
							$.gx.parseResult(rst);
							$(form).find('input:submit').each(function() {
								$(this).attr({
									'disabled': null,
									'_value': null,
									'value': $(this).attr('_value')
								});
							});
						}
					},
					error:function(xhr, text, error) {
						if(cb_error) {
							cb_error.call(form, xhr, text, error);
						} else {
							$.gx.parseError(xhr, text, error);
						}
					}
				});//end of .ajaxForm
			});//end of .each
			return $form;
		},
		ajaxGet:function(url, options) {
			if(!url) return;
			url = $.gx.urlAppend(url, {ajax:"yes"});
			if(typeof options != 'object') options = {};
			$.ajax($.extend({
				context:this,
				dataType:'JSON',
				error:$.gx.parseError,
				success:$.gx.parseResult,
				type:'GET',
				url:url
			}, options));
		},
		lightbox:function(selector, callback) {
			var $obj = $.gx.parseSelector.call(this, selector);
			if(!$obj) return false;
			if(!$.browser.msie){//fix textarea
				var $t = $obj.filter('textarea').add($obj.find('textarea').get());
				$t.text($t.val());
			}
			var $obj_clone = $obj.clone();
			if(typeof callback == 'function') $obj_clone = callback.call($obj_clone, $obj_clone);
			var $dialog = $("<div></div>");
			$dialog.appendTo('body');
			var w = $.gx.setRange($obj.width(), 400, 800);
			var h = $.gx.setRange($obj.height(), 300, 600);
			$obj_clone.width(w).height(h).appendTo($dialog);
			$dialog.dialog({
				modal:true,
				resizable:false,
				width:w+30,
				height:h+50,
				close:function() {
					$(this).find('textarea').text($(this).find('textarea').val().replace(/(\r\n)|\r|\n/g,"\r"));
					$obj.replaceWith($obj_clone.width($obj.width()).height($obj.height()).dblclick($.gx.lightbox));
					$(this).remove();
				}
			});
		},
		openDialog: function(url, target, options) {
			if(!target) target='_blank';
			if(typeof options != 'object') options = {};
			options = $.extend({
				modal:true,
				resizable:false,
				width:600,
				height:450,
				autoOpen:false,
				autoClose:false,
				dialogClass:'body'
			}, options);
			//init dialog
			if(!$.gx.openDialog.dialogs) $.gx.openDialog.dialogs = {};
			if($.gx.openDialog.dialogs['_blank']) {
				$.gx.openDialog.dialogs['_blank'].dialog('destroy').remove();
				$.gx.openDialog.dialogs['_blank'] = null;
			}
			if(!$.gx.openDialog.dialogs[target] || target=='_blank') {
				$.gx.openDialog.dialogs[target] = $('<div></div>');
				$.gx.openDialog.dialogs[target].dialog(options);
			}
			//url = $.gx.urlAppend(url, {ajax:"yes"});
			$.getJSON(url, {ajax:"yes"}, function(rst){
				if(rst.status==1) {					
					$.gx.openDialog.dialogs[target].dialog('open').html(rst.data).find('.main').width(options.width-30);
					if(options.autoClose) {
						$.gx.openDialog.dialogs[target].one('ajaxStart', function() {
							$.gx.closeDialog(target);
						});
					}
				} else if(rst.status==2) {//showMessage
					var msg = rst.info;
					var fwd = rst.data;
					$.gx.showMessage(msg, fwd)
				} else {
					$.gx.showMessage("服务器内部错误 ");
				}
			});
		},
		closeDialog:function(target) {
			if(!target) {
				for(var k in $.gx.openDialog.dialogs) {
					if(!$.gx.openDialog.dialogs[k]) continue;
					$.gx.openDialog.dialogs[k].dialog('destroy').remove();
					$.gx.openDialog.dialogs[k] = null;
				}
				return;
			}
			if(!$.gx.openDialog.dialogs[target]) return;
			$.gx.openDialog.dialogs[target].dialog('destroy').remove();
			$.gx.openDialog.dialogs[target] = null;
			return;
		},
		makeGrid:function(selector, api, ds, options, param) {
			var $obj = $.gx.parseSelector.call(this, selector);
			if(!$obj) return false;
			$obj.each(function() {
				var T = this;
				T.grid = $.extend({
					$table:$('<table></table>'),
					api:api,
					ds:ds,
					query:$.extend({
						ac:"get",
						page:1,
						pp:10
					}, param),
					width:800,
					//functions
					updateQuery:function(param) {
						//if there is sth new, set page=1
						if(param&&!param.page) param.page=1;
						$.extend(T.grid.query, param);
					},
					getData:function(param) {
						T.grid.updateQuery(param);
						$.get(T.grid.api, T.grid.query, T.grid.fillTable, 'json');
					},
					//ajax callback to fill the table
					fillTable:function(obj, status) {
						if(obj.status<0) {
							$.gx.showMessage(obj.info);
							return;
						}
						var $tbody = T.grid.$table.find('tbody');
						$tbody.find('*').remove();
						var data = obj.data;
						for(var k in data) {
							var $tr = $('<tr />').addClass('row_'+k);
							var d = data[k];
							for(var k2 in T.grid.ds) {
								var $td = $("<td />");
								var f = T.grid.ds[k2];
								$td.html(d[f['field']]);
								$tr.append($td);
							}
							$tr.append($("<td></td>")
								.append($("<button class='jqbutton fl' _icon='pencil'>修改</button>").click(function() {
									T.grid.editRow(k);
								}))
								.append("<button class='jqbutton fl' _icon='trash'>删除</button>")
							);
							$tbody.append($tr);
						}
						T.grid.applyCSS();
					},
					//edit single row
					editRow:function(k) {
						$('<div />').dialog({
							modal:true,
							draggable:false,
							resizable:false,
							buttons:{
								'关闭':function() {
									$(this).dialog('destroy');
								}
							}//end of buttons{}
						});
					},
					//apply css to table
					applyCSS:function() {						
						$(T).addClass('ui-widget ui-widget-content ui-corner-all').css({margin:'auto'}).width(T.grid.width)
							.find('table').width('100%').css({border:0}).end()
							.find('thead').addClass('ui-helper-reset ui-widget-header ui-corner-all')
								.find('td').css({padding:'0.5em'}).end()
							.end()
						;
						$.gx.fixUI();
					},
					
				}, options);//end of T.grid
				$(T).addClass('datagrid').append(T.grid.$table);
				//append the thead
				var $tr = $("<tr />");
				for(var k in T.grid.ds) {
					var $td = $("<td />");
					var f = T.grid.ds[k];
					$td.html(f.name);//.css(f.css);
					$tr.append($td);
				}
				$tr.append('<td width="150px" align="center" />');
				T.grid.$table.append($("<thead />").append($tr));
				T.grid.$table.append("<tbody />");
				T.grid.applyCSS();
				T.grid.getData();
			});//end of each()
		}//end of makeGrid(){}
	}//end of gx{}
});

/*********************************************/